<?php
   $app_id = "268811116482452";
   $app_secret = "55b33d9c8d53e8f2c1e1fca00917659c";
   $my_url = "http://apps.facebook.com/video-news-feed/e.php";

   $bad = array("\"", "\r", "\n", "\'");
   $good = array(" ", " ", " ", " ");
   
   session_start();
   $code = $_REQUEST["code"];

   if(empty($code)) {
     $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
     $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&scope=user_photo_video_tags,read_stream". "&state="
       . $_SESSION['state'];

     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

   if($_REQUEST['state'] == $_SESSION['state']) {
     $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

	$graph_url = "https://graph.facebook.com/me/home?access_token=". $params['access_token'];

        ////////////////////////

        $data = json_decode(file_get_contents($graph_url))->data;

	// create script string to append to content. First create the value array in JavaScript.
	$script = $script . "\n" . '<script type="text/javascript"> '. "\nvar newsFeedMessages = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
                              if(strcmp($value->type,"status")==0)
        	    		$script = $script . "\"" . addslashes($value->message) . "\",";
 			      else if(strcmp($value->type,"photo")==0) 
        	    		$script = $script . "\"" . $value->picture . "\",";
 			      else if(strcmp($value->type,"link")==0) 
        	    		$script = $script . "\"" . $value->link . "\",";
 			      else if(strcmp($value->type,"video")==0) 
        	    		$script = $script . "\"" . $value->link . "\",";
        		}
        		else {
                              if(strcmp($value->type,"status")==0) 
        	    		$script = $script . "\"" . addslashes($value->message) . "\");\n";
 			      else if(strcmp($value->type,"photo")==0) 
        	    		$script = $script . "\"" . $value->picture . "\");\n";
 			      else if(strcmp($value->type,"link")==0) 
        	    		$script = $script . "\"" . $value->link . "\");\n";
 			      else if(strcmp($value->type,"video")==0) 
        	    		$script = $script . "\"" . $value->link . "\");\n";

        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
              if(strcmp($value->type,"status")==0) 
    		$script = $script . "1);\nnewsFeedMessages[0]=\"" . addslashes($data[0]->message) . "\";\n";
	      else if(strcmp($value->type,"photo")==0) 
    		$script = $script . "1);\nnewsFeedMessages[0]=\"" . $data[0]->picture . "\");\n";
	      else if(strcmp($value->type,"link")==0) 
    		$script = $script . "1);\nnewsFeedMessages[0]=\"" . $data[0]->link . "\");\n";
	      else if(strcmp($value->type,"video")==0) 
    		$script = $script . "1);\nnewsFeedMessages[0]=\"" . $data[0]->link . "\");\n";

	}

        ////////////////////////


	$script = $script . "\n" . "var newsFeedNames = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->from->name . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->from->name . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nnewsFeedNames[0]=\"" . $data[0]->from->name . "\";\n";
	}
	
        //////////////////////////

	$script = $script . "\n" . "var newsFeedProfileImages = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->from->id . "/picture\",";
        		}
        		else {
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->from->id . "/picture\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nnewsFeedProfileImages[0]=\"https://graph.facebook.com/" . $data[0]->from->id . "/picture\";\n";
	}

        ////////////////////////////


	$script = $script . "\n" . "var newsPictures = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->picture . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->picture . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nnewsPictures[0]=\"" . $data[0]->picture . "\";\n";
	}


        ////////////////////////////


	$script = $script . "\n" . "var newsFeedTimes = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->updated_time . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->updated_time . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nnewsFeedTimes[0]=\"" . $data[0]->updated_time . "\";\n";
	}

        ////////////////////////////


	$script = $script . "\n" . "var newsFeedTypes = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->type . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->type . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nnewsFeedTypes[0]=\"" . $data[0]->updated_time . "\";\n";
	}


       /////////////////////////////
       // PHOTOS
       ////////////////////////////

       $photo_url = "https://graph.facebook.com/me/photos?access_token=" . $params['access_token'];


        $data = json_decode(file_get_contents($photo_url))->data;
 

	$script = $script . "\n" . "var photoUploaderNames = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->from->name . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->from->name . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nphotoUploaderNames[0]=\"" . $data[0]->from->name . "\";\n";
	}
	
       ///////////////////////////////

	$script = $script . "\n" . "var photoTitles = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . addslashes($value->name) . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . addslashes($value->name) . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nphotoTitles[0]=\"" . addslashes($data[0]->name) . "\";\n";
	}

       ///////////////////////////////

	$script = $script . "\n" . "var photos = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->images[1]->source . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->images[1]->source . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nphotos[0]=\"" . $data[0]->images[1]->source . "\";\n";
	}
	
       ///////////////////////////////

	$script = $script . "\n" . "var photosProfilePictures = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->from->id . "/picture\",";
        		}
        		else {
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->from->id . "/picture\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nphotosProfilePictures[0]=\"https://graph.facebook.com/" . $data[0]->from->id . "/picture\";\n";
	}


        ///////////////////////////////
        // FRIENDS
        ///////////////////////////////
 

	$friends_url = "https://graph.facebook.com/me/friends?access_token=". $params['access_token'];

        $data = json_decode(file_get_contents($friends_url))->data;
 
	$script = $script . "\n" . "var friendNames = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"" . $value->name . "\",";
        		}
        		else {
        	    		$script = $script . "\"" . $value->name . "\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nfriendNames[0]=\"" . $data[0]->name . "\";\n";
	}
	
       ///////////////////////////////

	$script = $script . "\n" . "var friendPictures = new Array(";
	if (count($data)>1) {
    		foreach ($data as $key => $value){
        		if ($key < (count($data)-1)){
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->id . "/picture\",";
        		}
        		else {
        	    		$script = $script . "\"https://graph.facebook.com/" . $value->id . "/picture\");\n";
        		}
    		}
	}
	else {  // can't create an array that just has one integer element using Array()
    		$script = $script . "1);\nfriendPictures[0]=\"https://graph.facebook.com/" . $data[0]->id . "/picture\";\n" ;
	}
	
       ///////////////////////////////


        ///////////////////////////////
	$script = $script . "</script>";

     	echo($script);
   }
   else {
     echo("The state does not match. You may be a victim of CSRF.");
   }?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://www.html5canvastutorials.com/libraries/kinetic2d-v1.0.2.js">

</script>
<script src="navigation.js"></script>
<script type="text/javascript">
var canvas;
var context;
var canvasWidth;
var canvasHeight;
var MODE;
var PICTURE_MODE = 0, STATUS_MODE = 1, FRIENDSHIP_MODE = 2;
var NUM_IMAGES = 4;
var NUM_STATUSES = 5;
var NUM_FRIENDSHIPS = 4;
var images = new Array();
var statuses = new Array();
var friendships = new Array();
var friendIndex = 0;
var imageIndex = 0;
var statusIndex = 0;
var modeChangeReady = true;

var statusArray = new Array("I always liked the story of Noah's Ark and the idea of starting anew by rescuing the things you like and leaving the rest behind." + 
"Zach Braff", "brothers to the end Cory Lu", "Dustin Starks!!!!! where is everyone else?!?!!:)");
var statusNames = new Array("Brian Drout", "Pari Lingampally", "Aimee Goodew");

function FacebookImage(name, text, src, x, y) {
	this.name = name;
	this.text = text;
	this.img = new Image();
	this.img.src = src;
	this.width = 410//this.img.width + 10;
	this.height = 430//this.img.height + 30;
	this.x = x;
	this.y = y;
	this.velocity = 700;
	this.acceleration = -5;
	
	this.draw = function() {
		context.fillStyle = "#FFF";
		context.strokeStyle = "#DDD";
		context.lineWidth = 1;
		context.strokeRect(this.x, this.y + 10, this.width, this.height);
		context.drawImage(this.img, this.x + 5, this.y + 15, 400, 400);
		context.fillStyle = "#038";
		context.font = "bold 15px sans-serif";
		context.fillText(this.name, this.x + 5, this.y + 5);
		context.fillStyle = "#000";
		context.font = "bold 10px sans-serif";
		context.fillText(this.text, this.x + 5, this.y + this.height);
	}
}

function FacebookStatus(text, name, src, x, y) {
	this.textArray = getLines(context, text, 300, "14px sans-serif");
	this.name = name;
	this.img = new Image();
	this.img.src = src;
	this.x = x;
	this.y = y;
	this.height = 40 + 20 * this.textArray.length;

	this.draw = function() {
		context.fillStyle = "#EEE";
		context.fillRect(this.x, this.y, 400, this.height);
		context.strokeStyle = "#CCC";
		context.lineWidth = 3;
		context.strokeRect(this.x, this.y, 400, this.height);
		context.fillStyle = "#000";
		context.font = "14px sans-serif";
		var height = 45;
		for (var i = 0; i < this.textArray.length; i++) {
			context.fillText(this.textArray[i],this.x + 80, this.y + height);
			height += 20;
		}
		context.fillStyle = "#038";
		context.font = "bold 18px sans-serif";
		context.fillText(this.name, this.x + 80, this.y + 25);
		context.drawImage(this.img, this.x + 10, this.y + 10);
	}
}

function FacebookFriendship(name1, name2, src1, src2, y) {
	this.name1 = name1;
	this.name2 = name2;
	this.img1 = new Image();
	this.img1.src = src1;
	this.img2 = new Image();
	this.img2.src = src2;
	this.friend_icon = new Image();
	this.friend_icon.src = "friend_added.png";
	this.y = y;
	this.x1 = 100;
	this.x2 = canvasWidth - 200;
	this.width = 60;
	this.height = 60;
	this.lines = new FriendshipLines(this.x1 + this.width, this.x2, this.y + this.height / 2);
	this.showIcon = false;
	
	this.draw = function() {
		context.fillStyle = "#038";
		context.font = "bold 12px sans-serif";
		context.fillText(this.name1, this.x1 + 2, this.y - 8);
		context.fillText(this.name2, this.x2 + 2, this.y - 8);
	
		context.fillStyle = "#FFF";
		context.strokeStyle = "#CCC";
		context.lineWidth = 1;
		context.strokeRect(this.x1, this.y, this.width, this.height);
		context.strokeRect(this.x2, this.y, this.width, this.height);
		context.drawImage(this.img1, this.x1 + 5, this.y + 5);
		context.drawImage(this.img2, this.x2 + 5, this.y + 5);
		this.lines.draw();
		if (this.showIcon) {
			var middlex = ((this.x1 + this.width) + this.x2) / 2;
			var middley = this.y + this.height / 2;
			context.beginPath();
			context.arc(middlex,middley,20,0,2*Math.PI,false);
			context.fillStyle = "#EEE";
			context.fill();
			context.lineWidth = 2;
			context.strokeStyle = "#CCC";
			context.stroke();
			context.closePath();
			context.drawImage(this.friend_icon, middlex - 13, middley - 15, 26, 30);
		}
	}
}

function FriendshipLines(startx, endx, y) {
	this.startx = startx;
	this.leftx = startx;
	this.endx = endx;
	this.rightx = endx;
	this.y = y;
	
	this.draw = function() {
		context.strokeStyle = "#CCC";
		context.beginPath();
		context.moveTo(this.startx, this.y);
		context.lineTo(this.leftx, this.y);
		context.stroke();
		context.closePath();
		context.beginPath();
		context.moveTo(this.endx, this.y);
		context.lineTo(this.rightx, this.y);
		context.stroke();
		context.closePath();
	}
}

// Code from StackOverflow **User: mizar
function getLines(ctx,phrase,maxPxLength,textStyle) {
    var wa=phrase.split(" "),
        phraseArray=[],
        lastPhrase="",
        l=maxPxLength,
        measure=0;
    ctx.font = textStyle;
    for (var i=0;i<wa.length;i++) {
        var w=wa[i];
        measure=ctx.measureText(lastPhrase+w).width;
        if (measure<l) {
			if (i != 0)
				lastPhrase+=(" "+w);
			else
				lastPhrase+=(w);
        }else {
            phraseArray.push(lastPhrase);
            lastPhrase=w;
        }
        if (i===wa.length-1) {
            phraseArray.push(lastPhrase);
            break;
        }
    }
    return phraseArray;
}

function moveImages() {
	for (var i = 0; i < NUM_IMAGES; i++) {
		var tempImage = images[i];
		// tempImage.velocity += tempImage.acceleration;
		// if (tempImage.velocity < 0) {
			// tempImage.acceleration = -tempImage.acceleration;
		// }
		tempImage.x += 6;
		//tempImage.x += tempImage.velocity * canvas.getTimeInterval() / 1000;
	}
}

function newMode() {
	// Clean up past mode
	switch (MODE) {
		case PICTURE_MODE:
			MODE = STATUS_MODE;
			images = new Array();
			break;
		case STATUS_MODE:
			MODE = FRIENDSHIP_MODE;
			statuses = new Array();
			break;
		case FRIENDSHIP_MODE:
			MODE = PICTURE_MODE;
			friendships = new Array();
			break;
		default:
			MODE = PICTURE_MODE;
	}
	
	// Randomly pick mode
	//MODE = Math.floor(Math.random() * 3);
	//MODE = STATUS_MODE;
	//MODE = PICTURE_MODE;
	//MODE = FRIENDSHIP_MODE;
	switch (MODE) {
		case PICTURE_MODE:
			createImages();
			break;
		case STATUS_MODE:
			createStatuses();
			break;
		case FRIENDSHIP_MODE:
			createFriendships();
			break;
	}
}

function createImages() {
	for (var i = 0; i < NUM_IMAGES; i++) {
		if (photoUploaderNames[imageIndex] == undefined)
			imageIndex = 0;
		images[i] = new FacebookImage(photoUploaderNames[imageIndex], photoTitles[imageIndex], photos[imageIndex], -(i + 1) * 600, 20);
		imageIndex++;
	}
}

function createStatuses() {
	var y = 50;
	for (var i = 0; i < NUM_STATUSES; i++) {
		if(newsFeedTypes[statusIndex] == "status") {
			statuses[i] = new FacebookStatus(newsFeedMessages[statusIndex], newsFeedNames[statusIndex], newsFeedProfileImages[statusIndex], -300, y);
			y += 100;
		}
		else {
			i--;
		}
		statusIndex++;
	}
}

function createFriendships() {
	for (var i = 0; i < NUM_FRIENDSHIPS; i++) {
		friendships[i] = new FacebookFriendship(friendNames[friendIndex], friendNames[friendIndex + 1], friendPictures[friendIndex], friendPictures[friendIndex + 1], (i + 1) * 100);
		friendIndex += 2;
	}
}

function moveFriendships() {
	for (var i = 0; i < NUM_FRIENDSHIPS; i++) {
		if (canvas.getTime() % 7000 > i * 400) {
			var lines = friendships[i].lines;
			if (lines.leftx < lines.rightx) {
				lines.leftx += 2;
				lines.rightx -= 2;
			} else {
				friendships[i].showIcon = true;
			}
		}
	}
}

function moveStatuses() {
	for (var i = 0; i < NUM_STATUSES; i++) {
		statuses[i].x += 3;
	}
}

function drawStatuses() {
	for (var i = 0; i < NUM_STATUSES; i++) {
		statuses[i].draw();
	}
}

function drawImages() {
	for (var i = 0; i < NUM_IMAGES; i++) {
		images[i].draw();
	}
}

function drawFriendships() {
	context.font = "bold 24px sans-serif";
	context.fillStyle = "#038";
	context.fillText("New Friendships", (canvasWidth / 2) - 100, 50);
	for (var i = 0; i < NUM_FRIENDSHIPS; i++) {
		friendships[i].draw();
	}
}

// Called continuously
function updateCanvas(){

	// Change mode
	if (canvas.getTime() % 7000 < 1000 && modeChangeReady ) {
		newMode();
		modeChangeReady = false;
	}
	if (canvas.getTime() % 7000 > 5000) {
		modeChangeReady = true;
	}
	
	// Do stuff
	switch (MODE) {
		case PICTURE_MODE: 	
			moveImages();
			drawImages();
			break;
		case STATUS_MODE:
			moveStatuses();
			drawStatuses();
			break;
		case FRIENDSHIP_MODE:
			moveFriendships();
			drawFriendships();
			break;
	}
}

// Setup canvas
window.onload = function(){
	canvas = new Kinetic_2d("myCanvas");
	canvas.getCanvas().width = document.width - 20;
	canvas.getCanvas().height = document.height - 20;
	canvasWidth = document.width - 20;
	canvasHeight = document.height - 20;
	context = canvas.getContext();
	
	canvas.setDrawStage(function(){
		canvas.clear();
		updateCanvas();
	});
	canvas.startAnimation();
};</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="200">
        </canvas></body>
</html>
